<template>
  <div :class="class" v-loading="shareLoading">
    <div class="open-share-box">
      <div class="set-item">
        <span class="item-name">{{ $t('message.text.isShare') }}</span>
        <jvs-switch v-model="docInfo.share" @change="shareChange"
          :disabled="!$permissionRole('document_share', docInfo.dcIdentifying)"></jvs-switch>
      </div>
      <div class="set-item-tips">{{ $t('message.text.sensitiveDocumentCaution') }}</div>
    </div>
    <template v-if="docInfo.share">
      <div class="validity-box">
        <div class="validity-title">{{ $t('message.text.setExpiration') }}</div>
        <div class="validity-check-box">
          <div class="validity-item" :class="[!$permissionRole('document_share', docInfo.dcIdentifying) && 'disabled']"
            v-for="(item, index) in validityList" :key="index" @click="changeValidity(item)">
            <svg class="check-box-svg" aria-hidden="true">
              <use
                v-bind:xlink:href="`#${docInfo.shareTimeType == item.value ? 'keowledge-a-zu3772' : 'keowledge-a-yuanxing5biankuang'}`">
              </use>
            </svg>
            <span class="validity-label">{{ $t(item.label) }}</span>
          </div>
        </div>
      </div>
      <div class="line"></div>
      <div class="title-box">
        <div>{{ $t('message.text.weChatScanShow') }}</div>
        <div>{{ $t('message.text.linkShare') }}</div>
      </div>
      <div class="share-box" v-loading="urlChangeLoading">
        <div class="qCode-box" :id="initId">
          <div :id="rendeId"></div>
        </div>
        <div class="address-box">
          <div>
            <div class="share-show-text">
              <div class="show-icon">
                <i class="knowledge-iconfont keowledge-fuzhilianjie"></i>
              </div>
              <el-popover :visible="showVisible" :disabled="!$permissionRole('document_share', docInfo.dcIdentifying)"
                popper-class="url-type-popper" placement="bottom" width="202px">
                <div class="show-url-type-list" v-click-outside="onClickOutside">
                  <div v-for="(item, index) in showUrlType" :key="index" class="url-type-item"
                    @click="changeUrlType(item)" :class="[showTypeUrl == item.value && 'url-type-itme-active']">
                    <svg class="check-icon">
                      <use xlink:href="#keowledge-xuanzhong"></use>
                    </svg>
                    <span class="text">{{ $t(item.label) }}</span>
                  </div>
                </div>
                <template #reference>
                  <div class="text" @click="openShowVisible">
                    <span>{{ $t(showUrlTypeLabel) }}</span>
                    <i class="knowledge-iconfont keowledge-xiala-zhankai"></i>
                  </div>
                </template>
              </el-popover>
            </div>
            <div class="address-text">{{ filterAddressUrl }}</div>
          </div>
          <div class="action-box">
            <el-button style="background: #D7D8DB;" @click="doAction('reset')"
              :disabled="!$permissionRole('document_share', docInfo.dcIdentifying)">{{ $t('message.buttons.resetting') }}</el-button>
            <el-button type="primary" @click="doAction('copy')">{{ $t('message.buttons.copyLink') }}</el-button>
          </div>
        </div>
      </div>
      <div class="password-box">
        <div class="set-item" v-if="docInfo.share" style="margin-bottom:16px;">
          <span class="item-name">{{ $t('message.userInfo.setPassword') }}</span>
          <jvs-switch v-model="docInfo.security" @change="passwordChange"
            :disabled="!$permissionRole('document_share', docInfo.dcIdentifying)"></jvs-switch>
        </div>
        <div class="set-item" v-if="docInfo.security">
          <div class="input-box" :class="[shareFocus && 'input-box-focus']">
            <el-input v-model="docInfo.sharePassword" @focus="sharePassFocus" @blur="sharePassBlur"
              :readonly="!$permissionRole('document_share', docInfo.dcIdentifying)"></el-input>
          </div>
          <el-button type="primary" style="height:36px;" @click="passwordChange(true)"
            v-if="$permissionRole('document_share', docInfo.dcIdentifying)">{{ $t('message.buttons.generatePassword') }}</el-button>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch,
  onMounted,
  nextTick,
  getCurrentInstance,
  computed
} from 'vue'
import { enCodeKey } from "@/const/const"
import { encryption, decryption, randomLenNum } from "@/utils/util";
import type { ComponentInternalInstance } from 'vue'
import { useRouter } from "vue-router"
import QRCode from 'qrcodejs2-fix'
import { copyText } from '@/utils/util'
import { getByIdShareInfo, shareSetting, setLibrary } from '@/api/common'
import { $permissionRole } from '@/utils/role'
import { ClickOutside as vClickOutside } from 'element-plus'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const router = useRouter();
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any;
const emit = defineEmits(["update:docInfo", "change"])
const props = defineProps({
  docInfo: {
    type: Object,
    default() {
      return {}
    }
  },
  class: {
    type: String
  },
  openShare: {
    type: Boolean,
    default: true
  },
  initId: {
    type: String,
    default: "qCode-box"
  },
  rendeId: {
    type: String,
    default: 'qCodeBox'
  }
})
const addressUrl = ref('')
const shareFocus = ref(false)
const shareLoading = ref(false)
const showTypeUrl = ref('2')
onMounted(() => {
  if (props.docInfo.showShareLink && props.docInfo.share) {
    addressUrl.value = props.docInfo.showShareLink
    initQcode()
  }
})
watch(() => props.docInfo.share, (newV, oldV) => {
  if (newV) {
    addressUrl.value = props.docInfo.showShareLink
    initQcode()
  }
})
watch(() => props.docInfo.showShareLink, (newV, oldV) => {
  if (newV != oldV && newV && props.docInfo.share) {
    addressUrl.value = props.docInfo.showShareLink
    initQcode()
  }
})
watch(() => props.docInfo, (newV, oldV) => {
  if (newV.otherJson) {
    showTypeUrl.value = JSON.parse(newV.otherJson).urlType || '2'
  } else {
    showTypeUrl.value = '2'
  }
})
watch(() => props.openShare, (newV, oldV) => {
  if (newV && props.docInfo.share) {
    addressUrl.value = props.docInfo.showShareLink
    initQcode()
  }
})
const validityList = [
  { label: 'message.typeMenu.dayValidity7', value: 'SEVEN_DAYS' },
  { label: 'message.typeMenu.dayValidity30', value: 'THIRTY_DAY' },
  { label: 'message.typeMenu.perValidity', value: 'PERPETUAL' },
]
const showVisible = ref(false)
const showUrlType = ref([{
  label: 'message.typeMenu.notDisplaySuffix',
  value: '0'
}, {
  label: 'message.typeMenu.onlyDisplayFileName',
  value: '1'
}, {
  label: 'message.typeMenu.displayFileName',
  value: '2'
}])
const showUrlTypeLabel = computed(() => {
  let str = showUrlType.value.find(item => item.value == showTypeUrl.value)
  return str.label
})
const filterAddressUrl = computed(() => {
  if (addressUrl.value) {
    switch (showTypeUrl.value) {
      case '0':
        return addressUrl.value.substring(0, addressUrl.value.indexOf('《'))
        break;
      case '1':
        return addressUrl.value.substring(0, addressUrl.value.indexOf('('))
        break
      default:
        return addressUrl.value
        break;
    }
  } else {
    return addressUrl.value
  }
})
function init() {
  shareLoading.value = true
  getByIdShareInfo(props.docInfo.id).then(res => {
    if (res.data.code == 0) {
      let pwd = '', security = false
      if (res.data.data.sharePassword) {
        let temp = decryption({
          data: { pass: res.data.data.sharePassword },
          key: enCodeKey,
          param: ["pass"]
        });
        pwd = temp.pass
        security = true
      }
      emit("update:docInfo", {
        ...props.docInfo,
        shareTimeType: res.data.data.shareTimeType || 'PERPETUAL',
        security: security,
        sharePassword: pwd
      })
      addressUrl.value = `${location.origin}/#/share/` + res.data.data.shareLink
      initQcode()
    }
  }).finally(f => {
    shareLoading.value = false
  })
}
function initQcode() {
  if (props.docInfo.share) {
    nextTick(() => {
      const width = document.getElementById(props.initId).clientWidth - 48,
        height = document.getElementById(props.initId).clientHeight - 48
      $(`#${props.rendeId}`).html("")
      let qrcode = new QRCode(props.rendeId, {
        width: width,
        height: height,
        text: filterAddressUrl.value, // 二维码地址
        colorDark: "#000",
        colorLight: "#fff",
        correctLevel: QRCode.CorrectLevel.L // 这里容错等级只能是L 或者 M
      })
    })
  }
}
function changeValidity(item) {
  if (!$permissionRole('document_share', props.docInfo.dcIdentifying)) return
  changeVal({
    shareTimeType: item.value
  })
  nextTick(() => {
    doAction('validity')
  })
}
function changeVal(item) {
  emit("update:docInfo", {
    ...props.docInfo,
    ...item
  })
  emit('change', {
    ...props.docInfo,
    ...item
  })
}
function doAction(type) {
  let obj
  switch (type) {
    case 'copy':
      copyText(filterAddressUrl.value, () => {
        proxy.$onePrompt.$oneNotify({
          title: $t('message.prompt'),
          message: $t('message.message.copyLinkSuccess'),
          position: "bottom-right",
          type: "success"
        })
      })
      break;
    case 'validity':
      obj = {
        id: props.docInfo.id,
        dcId: props.docInfo.id,
        settingType: 'SHARE',
        shareLinkOriginal: props.docInfo.shareLinkOriginal,
        sharePassword: '',
        share: props.docInfo.share,
        updatePassWord: false,
        shareTimeType: props.docInfo.shareTimeType
      }
      if (!props.docInfo.shareLinkOriginal) {
        obj.shareLinkOriginal = `knId=${props.docInfo.knowledgeId}&type=${props.docInfo.type}&nameSuffix=${props.docInfo.nameSuffix || ''}&docId=${props.docInfo.docId || props.docInfo.id}`
      }
      sendChangeShare(obj, 'validity')
      break;
    case 'reset':
      obj = {
        id: props.docInfo.id,
        dcId: props.docInfo.id,
        settingType: 'CREATE_URL',
        shareLinkOriginal: '',
        sharePassword: '',
        updatePassWord: false,
        share: props.docInfo.share,
        shareTimeType: props.docInfo.shareTimeType || 'PERPETUAL'
      }
      obj.shareLinkOriginal = `knId=${props.docInfo.knowledgeId}&type=${props.docInfo.type}&nameSuffix=${props.docInfo.nameSuffix || ''}&docId=${props.docInfo.docId || props.docInfo.id}`
      sendChangeShare(obj, 'reset')
      break
    default:
      break;
  }
}
function sendChangeShare(obj, type) {
  shareLoading.value = true
  let temp = encryption({
    data: obj,
    key: enCodeKey,
    param: ["sharePassword"]
  });
  shareSetting(temp).then(res => {
    if (res.data.code == 0) {
      let message
      if (type == 'changeshare') {
        proxy.$eventBus.$emit("refreshItemStatus", 'valChange', {
          id: props.docInfo.id,
          key: 'share',
          changeVal: obj.share
        })
        if (obj.share) {
          message = $t('message.message.openShare')
          addressUrl.value = `${location.origin}/#/share/` + res.data.data.shareLink
        } else {
          message = $t('message.message.closeShare')
        }
      } else if (type == 'validity') {
        message = $t('message.message.validityUpdate')
      } else if (type == 'password') {
        if (props.docInfo.security) {
          if (obj.sharePassword != props.docInfo.sharePassword) {
            message = $t('message.message.openSharePassword')
          } else {
            message = $t('message.message.updateSharePassword')
          }
        } else {
          message = $t('message.message.closeSharePassword')
        }
      } else {
        message = $t('message.message.resetShareLink')
      }
      if (obj.share) {
        addressUrl.value = `${location.origin}/#/share/` + res.data.data.shareLink
      }
      if (type == 'password') {
        changeVal({
          sharePassword: obj.sharePassword
        })
      } else {
        if (obj.share) {
          changeVal({
            showShareLink: addressUrl.value
          })
        }
      }
      initQcode()
      proxy.$onePrompt.$oneNotify({
        title: $t('message.prompt'),
        message: message,
        position: "bottom-right",
        type: "success"
      })
    }
  }).finally(f => {
    shareLoading.value = false
  })
}
function sharePassFocus() {
  shareFocus.value = true
}
function sharePassBlur() {
  shareFocus.value = false
  passwordChange(true, props.docInfo.sharePassword)
}
function passwordChange(val, pwd) {
  changeVal({
    security: val
  })
  let password
  if (pwd) {
    password = pwd
  } else {
    if (val) {
      password = randomLenNum()
    } else {
      password = ''
    }
  }
  let obj = {
    id: props.docInfo.id,
    dcId: props.docInfo.id,
    settingType: 'PWD',
    shareLinkOriginal: `knId=${props.docInfo.knowledgeId}&type=${props.docInfo.type}&nameSuffix=${props.docInfo.nameSuffix || ''}&docId=${props.docInfo.docId || props.docInfo.id}`,
    sharePassword: password,
    share: props.docInfo.share,
    updatePassWord: true,
    shareTimeType: 'PERPETUAL'
  }
  sendChangeShare(obj, 'password')
}
function shareChange(val) {
  let obj = {
    id: props.docInfo.id,
    dcId: props.docInfo.id,
    settingType: '',
    shareLinkOriginal: '',
    sharePassword: '',
    share: val,
    updatePassWord: false,
    shareTimeType: 'PERPETUAL'
  }
  changeVal({
    share: val
  })
  if (val) {
    obj.settingType = 'CREATE_URL'
    obj.shareLinkOriginal = `knId=${props.docInfo.knowledgeId}&type=${props.docInfo.type}&nameSuffix=${props.docInfo.nameSuffix || ''}&docId=${props.docInfo.docId || props.docInfo.id}`
  } else {
    changeVal({
      security: false
    })
    obj.settingType = 'SHARE'
  }
  sendChangeShare(obj, 'changeshare')
}
function openShowVisible() {
  showVisible.value = !showVisible.value
}
function onClickOutside() {
  showVisible.value = false
}
const urlChangeLoading = ref(false)
function changeUrlType(item) {
  urlChangeLoading.value = true
  showVisible.value = false
  setLibrary({
    ...props.docInfo,
    otherJson: JSON.stringify({
      ...JSON.parse(props.docInfo.otherJson || '{}'),
      urlType: item.value
    })
  }).then(res => {
    if (res.data.code == 0) {
      showTypeUrl.value = item.value
      changeVal({
        otherJson: JSON.stringify({
          ...JSON.parse(props.docInfo.otherJson || '{}'),
          urlType: item.value
        })
      })
      // // 修改了值后要同步修改树
      proxy.$eventBus.$emit("refreshItemStatus", 'valChange', {
        id: props.docInfo.id,
        key: 'otherJson',
        changeVal: JSON.stringify({
          ...JSON.parse(props.docInfo.otherJson || '{}'),
          urlType: item.value
        })
      })
      initQcode()
    }
  }).finally(f => {
    urlChangeLoading.value = false
  })
}
defineExpose({
  init
})
</script>
<style lang="scss" scoped>
.doc-share-box {
  padding: 0px 24px !important;
  margin: 16px 0px;
}

.share-dialog-box {
  padding: 0px 32px;
  margin: 24px 0px;
}

.doc-share-box,
.share-dialog-box {
  .open-share-box {
    margin-bottom: 16px;

    .set-item {
      padding: 0px !important;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .item-name {
        color: #363b4c;
        font-size: 14px;
        @include SourceHanSansCN-Bold;
      }
    }

    .set-item-tips {
      padding: 0px !important;
      color: #6F7588;
      font-size: 12px;
    }
  }

  .password-box {
    margin-top: 16px;

    .set-item {
      padding: 0px !important;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .item-name {
        color: #363b4c;
        font-size: 14px;
        @include SourceHanSansCN-Bold;
      }

      .input-box {
        width: 100%;
        margin-right: 16px;
        background: #F5F6F7;
        border: 1px solid #f5f6f7;
        border-radius: 6px 6px 6px 6px;
        padding: 0px 4px;
        height: 36px;
        display: flex;
        align-items: center;

        ::v-deep(.el-input) {
          .el-input__wrapper {
            box-shadow: none !important;
            background-color: transparent !important;
          }
        }
      }

      .input-box-focus {
        border-color: #1E6FFF;
      }
    }
  }
}

.validity-box {
  box-sizing: border-box;
  background: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .validity-title {
    font-size: 14px;
    color: #363b4c;
  }

  .validity-check-box {
    display: flex;
    align-items: center;

    .validity-item {
      display: flex;
      align-items: center;
      margin-left: 32px;
      cursor: pointer;

      .check-box-svg {
        width: 14px;
        height: 14px;
      }

      .validity-label {
        color: #363B4C;
        font-size: 14px;
        @include SourceHanSansCN-Regular;
        margin-left: 8px;
      }
    }
  }
}

.line {
  height: 1px;
  background: #F5F6F7;
  margin: 24px 0px 16px;
}

.title-box {
  display: grid;
  grid-column-gap: 24px;
  grid-template-columns: repeat(2, 1fr);
  font-size: 14px;
  color: #363B4C;
}

.share-box {
  margin-top: 8px;
  display: grid;
  grid-column-gap: 24px;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: 264px;

  .qCode-box {
    background: #F5F6F7;
    border-radius: 6px 6px 6px 6px;
    padding: 24px;
    box-sizing: border-box;
    min-width: 264px;

    #qCodeBox {
      width: 100%;
      height: 100%;
    }
  }

  .address-box {
    background: #F5F6F7;
    border-radius: 6px 6px 6px 6px;
    padding: 24px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .share-show-text {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      .show-icon {
        width: 24px;
        height: 24px;
        background: #1E6FFF;
        border-radius: 4px 4px 4px 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;

        i {
          color: #FFFFFF;
          font-size: 14px;

        }
      }

      .text {
        font-size: 14px;
        color: #363b4c;
        padding: 2px 4px;

        &:hover {
          background: #E4E7EA;
          border-radius: 4px 4px 4px 4px;
          cursor: pointer;
        }
      }
    }

    .address-text {
      word-break: break-all;
      font-size: 14px;
      color: #363b4c;
    }

    .action-box {
      text-align: right;
    }
  }
}
</style>
<style lang="scss">
.url-type-popper {
  padding: 12px 0px !important;
}

.show-url-type-list {
  .url-type-item {
    display: flex;
    align-items: center;
    cursor: pointer;
    height: 32px;
    padding: 0px 8px;
    box-sizing: border-box;

    .check-icon {
      width: 16px;
      height: 16px;
      visibility: hidden;
      margin-right: 8px;
    }

    &:hover {
      background-color: #DDEAFF;
    }

    .text {
      font-size: 14px;
    }
  }

  .url-type-itme-active {
    color: #1E6FFF;

    .check-icon {
      visibility: visible;
    }
  }
}
</style>